const Adress = require("../models/Address")

/**
 * @description: 创建地址
 * @param {string} username
 * @param {Object} data 地址详细信息
 */
async function createAddress(username, data) {
  const newAddress = await Adress.create({ username, ...data })
  return newAddress
}
/**
 * @description: 获取收货地址列表
 * @param {String} username
 */
async function getAddressList(username) {
  const list = await Adress.find({ username }).sort({ updatedAt: -1 })
  return list
}
/**
 * @description: 获取单个地址
 * @param {String} id 地址id
 */
async function getAddressById(id) {
  const address = await Adress.findById({ _id: id })
  return address
}

/**
 * @description: 更新收货地址
 * @param {String} id
 * @param {String} username
 * @param {Object} data
 */
async function updateAddress(id, username, data) {
  const address = await Adress.findOneAndUpdate(
    { _id: id, username },
    { username, ...data },
    { new: true }
  )
  return address
}

module.exports = {
  createAddress,
  getAddressList,
  getAddressById,
  updateAddress
}
